package excel.util;

import excel.pojo.User;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author 秉性哥
 * @createTime 2022/10/28 15:15
 * @description 导出 Excel zip工具类
 */
public class ExportZipUtils {
    public static void exportExcelZip(String[]handers, List<User> list, HttpServletResponse response) throws IOException {
        //response 输出流
        ServletOutputStream out = response.getOutputStream();
        //压缩输出流---将response输出流填入压缩输出流
        ZipOutputStream zipOutputStream = new ZipOutputStream(out);
        try {
            for (int j = 0; j < 6; j++) {
                //创建工作簿
                SXSSFWorkbook wb = new SXSSFWorkbook();
                Sheet sheet = wb.createSheet("第一页");
                Row rowFirst = sheet.createRow(0);
                //写标题
                for (int i = 0; i < handers.length; i++) {
                    //获取第一行的每一个单元格
                    Cell cell = rowFirst.createCell(i);
                    //往单元格里面写入值
                    cell.setCellValue(handers[i]);
                }
                for (int i = 0;i < list.size(); i++) {
                    User user = list.get(i);
                    //创建行对象  参数：索引（从0开始）
                    Row row = sheet.createRow(i+1);
                    //设置对应单元格的值
                    row.setHeight((short)400);   // 设置每行的高度
                    //"序号","用户名","密码","结束时间","失败次数"
                    row.createCell(0).setCellValue(i+1);
                    row.createCell(1).setCellValue(user.getUsername());
                    row.createCell(2).setCellValue(user.getPassword());
                    row.createCell(3).setCellValue(user.getEnd_login_date());
                    row.createCell(4).setCellValue(user.getFail_count());
                }
                response.setContentType("application/octet-stream; charset=utf-8");
                response.setHeader("Content-Disposition", "attachment; filename=test.zip");
                //重点开始,创建压缩文件,并进行打包
                ZipEntry z = new ZipEntry("day1.xlsx");
                zipOutputStream.putNextEntry(z);
                //写入一个压缩文件---最后写文件
                wb.write(zipOutputStream);
            }
            zipOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //注意关闭顺序，否则可能文件错误，先开后关
            if (zipOutputStream != null) {
                zipOutputStream.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
}
